package org.zju.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.zju.demo.model.Order;
import org.zju.demo.model.Product;
import org.zju.demo.model.User;
import org.zju.demo.service.impl.OrderInfoImpl;
import org.zju.demo.service.impl.ProductInfoImpl;
import org.zju.demo.service.impl.UserImpl;
import org.zju.demo.service.intf.OrderInfoIntf;
import org.zju.demo.service.intf.ProductInfoIntf;
import org.zju.demo.service.intf.UserIntf;
import org.zju.demo.utils.Log;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * Created by ZJDX on 2015/9/1.
 */
@Controller
public class WebController {

    @RequestMapping(value = "/login.html")
    public ModelAndView index(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if(username == null || password == null || username.equals("")) {
            return new ModelAndView("/login");
        }
        UserIntf userService = new UserImpl();
        User user = userService.findByUsername(username);
        if (user== null || !password.equals(user.getPassword())) {
            String errorMessage = "用户名与密码不一致";
            return new ModelAndView("/login").addObject("errorMessage", errorMessage);
        }
        request.getSession().setAttribute("user", user);
        ModelAndView indexMVC = new ModelAndView("redirect:/index.html");
        return indexMVC;
    }

    //主页面
    @RequestMapping(value = "/index.html")
    public ModelAndView getAllInfo(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        if(user == null) {
            return new ModelAndView("/login");
        }
        ModelAndView mv = new ModelAndView("index");
        UserIntf userService = new UserImpl();
        ProductInfoIntf productService = new ProductInfoImpl();
        OrderInfoIntf orderService = new OrderInfoImpl();

        List<User> userList = userService.getAllUser();
        List<Product> productList = productService.getAllProduct();
        List<Order> orderList = orderService.getAllOrders();

        mv.addObject("userList", userList);
        mv.addObject("productList", productList);
        mv.addObject("orderList", orderList);
        mv.addObject("user_login", user);
        return mv;
    }

    //获取用户信息页面
    @RequestMapping(value = "/user.html")
    public ModelAndView getUserInfo(HttpServletRequest request) {
        UserIntf userService = new UserImpl();
        List<User> userList = userService.getAllUser();
        ModelAndView userMvc = new ModelAndView("/user");
        User user = (User)request.getSession().getAttribute("user");

        userMvc.addObject("user_info", user);
        userMvc.addObject("userList", userList);
        return userMvc;
    }

    //请求添加用户页面
    @RequestMapping(value = "/addUser.html")
    public ModelAndView getAddUser(HttpServletRequest request) {

        ModelAndView mv = new ModelAndView("/addUser");
        User user = (User) request.getSession().getAttribute("user");
        mv.addObject("user_info", user);

        return mv;
    }
    //添加用户，跳转到添加用户页面
    @RequestMapping(value = "/doAddUser.html", method = {RequestMethod.POST})
    public ModelAndView doAddUser(HttpServletRequest request, @ModelAttribute("user") User newUser) {

        UserIntf userService = new UserImpl();
        User tmpUser = userService.findByUsername(newUser.getUsername());
        ModelAndView mv = new ModelAndView("/addUser");
        User user = (User) request.getSession().getAttribute("user");
        mv.addObject("user_info", user);

        if(tmpUser == null) {
            newUser.setLevel(0);
            userService.saveOrUpdate(newUser);
            mv.addObject("message", "添加用户成功！");
        }
        else {
            mv.addObject("message", "用户名相同，添加失败！");
        }
        return mv;
    }

    //修改用户页面
    @RequestMapping(value = "/updateUser.html")
    public ModelAndView updateUser(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("/updateUser");
        User user = (User) request.getSession().getAttribute("user");
        mv.addObject("user_info", user);
        UserIntf userService = new UserImpl();
        List<User> userList = userService.getAllUser();
        mv.addObject("userList", userList);
        if (request.getParameter("message") != null) {
            System.out.println("message" + request.getParameter("message"));
            mv.addObject("message", request.getParameter("message"));
        }
        return mv;
    }

    //修改用户，跳转到修改用户页面
    @RequestMapping(value = "/doUpdateUser.html", method = {RequestMethod.POST})
    public ModelAndView doUpdateUser(HttpServletRequest request, @ModelAttribute("user") User modifyUser) {

        UserIntf userService = new UserImpl();
        User tmpUser = userService.findByUsername(modifyUser.getUsername());

        ModelAndView mv = new ModelAndView("redirect:/updateUser.html");
        User user = (User) request.getSession().getAttribute("user");
        mv.addObject("user_info", user);

        if(tmpUser == null || tmpUser.getUserId() == modifyUser.getUserId()) {
            userService.update(modifyUser);
            mv.addObject("message", "修改用户成功！");
        }
        else{
            mv.addObject("message", "未找到用户，修改失败！");
        }
        return mv;
    }

    //获取商品详细信息页面
    @RequestMapping(value = "/product.html")
    public ModelAndView getProductInfo(HttpServletRequest request) {
        ProductInfoIntf productService = new ProductInfoImpl();
        List<Product> productList = productService.getAllProduct();
        ModelAndView productMvc = new ModelAndView("/product");
        User user = (User)request.getSession().getAttribute("user");

        productMvc.addObject("user_info", user);
        productMvc.addObject("productList", productList);
        return productMvc;
    }

    //添加商品信息页面
    @RequestMapping(value = "/addProduct.html")
    public ModelAndView addProduct(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        ModelAndView mv = new ModelAndView("/addProduct");
        mv.addObject("user_info", user);
        return mv;
    }

    //添加商品详细信息，跳转到添加商品详细信息页面
    @RequestMapping(value = "/doAddProduct.html", method = {RequestMethod.POST})
    public ModelAndView doAddProduct(@RequestParam(value="image", required=false) MultipartFile file, HttpServletRequest request) {

        // 获得存储图片的文件夹
        String dirPath = "static" + "/" + "images" + "/" + "ProductImage";
        String imagePath = request.getSession().getServletContext().getRealPath("/WEB-INF");
        File imageSaveDir = new File(imagePath+"/"+dirPath);
        if (!imageSaveDir.exists()) {
            imageSaveDir.mkdirs();
        }
        // 获得图片的新名字
        String fileName = file.getOriginalFilename();
        String extensionName = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = String.valueOf(System.currentTimeMillis()) + extensionName;
        String storeFileName = imagePath + "/" + dirPath + "/" + newFileName;
        String dbFileName = dirPath + "/" + newFileName;
        File imageFile = new File(storeFileName);
        try{
            file.transferTo(imageFile);
        }catch (Exception e) {
            e.printStackTrace();
        }
        Product product = new Product();
        product.setProductName(request.getParameter("productName"));
        product.setCompany(request.getParameter("company"));
        product.setImageAddress(dbFileName);
        product.setPrice(Float.parseFloat(request.getParameter("price")));
        product.setAmount(Integer.parseInt(request.getParameter("amount")));
        product.setPopular(0f);
        product.setSaledNumber(0);
        ProductInfoIntf productService = new ProductInfoImpl();
        productService.addProduct(product);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/addProduct");
        mv.addObject("user_info", request.getSession().getAttribute("user"));
        mv.addObject("message", "Add Product Success");
        return mv;
    }

    //修改商品信息页面
    @RequestMapping(value = "/updateProduct.html")
    public ModelAndView updateProduct(HttpServletRequest request) {

        ModelAndView mv = new ModelAndView("/updateProduct");
        User user = (User) request.getSession().getAttribute("user");
        mv.addObject("user_info", user);
        ProductInfoIntf productInfoIntf = new ProductInfoImpl();
        List<Product> productList = productInfoIntf.getAllProduct();
        mv.addObject("productList", productList);
        if (request.getParameter("message") != null) {
            mv.addObject("message", request.getParameter("message"));
        }
        return mv;
    }

    //修改商品详细信息，跳转到修改商品详细信息页面
    @RequestMapping(value = "/doUpdateProduct.html", method = {RequestMethod.POST})
    public ModelAndView doUpdateProduct(@RequestParam(value="image", required=false) MultipartFile file, HttpServletRequest request) {
        // 获得存储图片的文件夹
        String dirPath = "static" + "/" + "images" + "/" + "ProductImage";
        String imagePath = request.getSession().getServletContext().getRealPath("/WEB-INF");
        File imageSaveDir = new File(imagePath+"/"+dirPath);
        if (!imageSaveDir.exists()) {
            imageSaveDir.mkdirs();
        }
        // 获得图片的新名字
        String fileName = file.getOriginalFilename();
        String extensionName = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = String.valueOf(System.currentTimeMillis()) + extensionName;
        String storeFileName = imagePath + "/" + dirPath + "/" + newFileName;
        String dbFileName = dirPath + "/" + newFileName;
        File imageFile = new File(storeFileName);
        try{
            file.transferTo(imageFile);
        }catch (Exception e) {
            e.printStackTrace();
        }
        ProductInfoIntf productService = new ProductInfoImpl();
        Product product = productService.findByProductId(Integer.parseInt(request.getParameter("productId")));
        product.setProductName(request.getParameter("productName"));
        product.setCompany(request.getParameter("company"));
//        product.setImageAddress(newFileName);
        product.setImageAddress(dbFileName);
        product.setPrice(Float.parseFloat(request.getParameter("price")));
        product.setAmount(Integer.parseInt(request.getParameter("amount")));

        productService.updateProduct(product);
        ModelAndView mv = new ModelAndView();

        mv.setViewName("redirect:/updateProduct.html");
        mv.addObject("user_info", request.getSession().getAttribute("user"));
        mv.addObject("message", "Add Product Success");

        return mv;
    }

    //查看订单页面
    @RequestMapping(value = "/order.html")
    public ModelAndView getOrderInfo(HttpServletRequest request) {
        OrderInfoImpl OrderService = new OrderInfoImpl();
        List<Order> orderList = OrderService.getAllOrders();
        ModelAndView orderMvc = new ModelAndView("/order");
        User user = (User)request.getSession().getAttribute("user");

        orderMvc.addObject("user_info", user);
        orderMvc.addObject("orderList", orderList);
        return orderMvc;
    }

    //修改订单页面
    @RequestMapping(value = "/updateOrder.html")
    public ModelAndView updateOrder(HttpServletRequest request) {
        OrderInfoIntf orderService = new OrderInfoImpl();
        List<Order> orderList = orderService.getAllOrders();

        ModelAndView mv = new ModelAndView("/updateOrder");
        User user = (User) request.getSession().getAttribute("user");
        mv.addObject("user_info", user);
        mv.addObject("orderList", orderList);
        if(request.getParameter("message")!=null) {
            mv.addObject("message", request.getParameter("message"));
        }
        return mv;
    }

    //添加用户，跳转到修改订单页面
    @RequestMapping(value = "/doUpdateOrder.html", method = {RequestMethod.POST})
    public ModelAndView doUpdateOrder(HttpServletRequest request) {

        OrderInfoIntf orderInfoService = new OrderInfoImpl();
        Order tmpOrder = orderInfoService.findById(Integer.parseInt(request.getParameter("orderId")));
        ModelAndView mv = new ModelAndView("redirect:/updateOrder.html");
        User user = (User) request.getSession().getAttribute("user");
        mv.addObject("user_info", user);

        if(tmpOrder != null) {
            tmpOrder.setStatus(request.getParameter("status"));
            orderInfoService.update(tmpOrder);
            mv.addObject("message", "修改订单成功！");
        }
        else{
            mv.addObject("message", "未找到订单，修改失败！");
        }
        return mv;
    }
}
